package com.book.web.controller.common;

import cn.hutool.core.util.RandomUtil;
import com.book.common.annotation.Anonymous;
import com.book.common.annotation.RateLimiter;
import com.book.common.constant.CacheConstants;
import com.book.common.core.controller.BaseController;
import com.book.common.core.domain.AjaxResult;
import com.book.common.core.redis.RedisCache;
import com.book.common.enums.LimitType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * 验证码接口
 * @author Bigboss
 * @create 2024-10-19 16:39
 */
@Api(tags = "验证码接口")
@RestController
@RequestMapping("/common")
public class CodeController extends BaseController {

    private final RedisCache redisCache;

    public CodeController(RedisCache redisCache) {
        this.redisCache = redisCache;
    }

    /**
     * 发送验证码
     * @param phone
     * @return
     *
     */
    @ApiOperation(value = "发送验证码")
    @RateLimiter(count = 60,limitType = LimitType.IP)
    @Anonymous
    @GetMapping("/sendCode/{phone}/{type}")
    public AjaxResult sendCode(@PathVariable String phone, @PathVariable String type){
        if(type.equals("register")){
            //1.验证码有效期固定5分钟，每隔一分钟可发送一次
            long expire = redisCache.getExpire(CacheConstants.PHONE_CODE_KEY + phone);
            if(expire >= 200){
                return error("请一分钟后再试");
            }
            //生成随机6为验证码
            final String code = RandomUtil.randomNumbers(6);
            //todo 这里可以增加调用阿里云发送code
            redisCache.setCacheObject(CacheConstants.PHONE_CODE_KEY + phone,code,300, TimeUnit.SECONDS);
            return success("发送成功"+code);
        }

        /**
         * 表示为重置密码
         */
        if(type.equals("reset")){
            //1.验证码有效期固定5分钟，每隔一分钟可发送一次
            long expire = redisCache.getExpire(CacheConstants.PHONE_CODE_RESET_PASSWORD_KEY + phone);
            if(expire >= 200){
                return error("请一分钟后再试");
            }
            //走到这里表示可以进行发送了
            //生成随机6为验证码
            final String code = RandomUtil.randomNumbers(6);
            //todo 这里可以增加调用阿里云发送code
            redisCache.setCacheObject(CacheConstants.PHONE_CODE_RESET_PASSWORD_KEY + phone,code,300, TimeUnit.SECONDS);
            return success("发送成功"+code);
        }
        return success("发送成功");
    }
}